﻿using System.Collections.Generic;
using MarriageFertility.Dialogs;
using MarriageFertility.Mcm;
using TaleWorlds.CampaignSystem;

namespace MarriageFertility.Behaviors
{
    public class FamilyAndRelationsBehavior : CampaignBehaviorBase
    {
        public override void RegisterEvents()
        {
            CampaignEvents.OnNewGameCreatedEvent.AddNonSerializedListener(this, OnInit);
            CampaignEvents.OnSessionLaunchedEvent.AddNonSerializedListener(this, OnSessionLoad);
            CampaignEvents.OnGivenBirthEvent.AddNonSerializedListener(this, ChildJoinMotherClan);
        }

        public override void SyncData(IDataStore dataStore)
        {
            dataStore.SyncData("CompetitionQuest", ref MarriageDialog.CompetitionQuest);
            dataStore.SyncData("PoetryTimes", ref PoetryDialog.PoetryTimes);
        }

        private void OnInit(CampaignGameStarter campaignGameStarter)
        {
            MarriageDialog.CompetitionQuest = null;
            if(MCMSettings.Instance.EnableClearSpouse) ClearSpouseAndChildren();
        }

        private void ClearSpouseAndChildren()
        {
            foreach (var hero in Hero.AllAliveHeroes)
            {
                if (hero.Spouse != null) hero.Spouse = null;
                if(hero.ExSpouses.Count>0) hero.ExSpouses.Clear();
                if(hero.Children.Count>0)
                {
                    foreach (var child in hero.Children)
                    {
                        child.Mother = null;
                        child.Father = null;
                    }
                    hero.Children.Clear();
                }
            }
        }
        
        
        private void OnSessionLoad(CampaignGameStarter campaignGameStart)
        {
            MarriageDialog.AddDialogs(campaignGameStart);
            PregnancyDialog.AddDialogs(campaignGameStart);
            SexFriendDialog.AddDialogs(campaignGameStart);
            ClanDialog.AddDialogs(campaignGameStart);
            NtrDialog.AddDialogs(campaignGameStart);
            DuelDialog.AddDialogs(campaignGameStart);
            PoetryDialog.AddDialogs(campaignGameStart);
        }

        private void ChildJoinMotherClan(Hero mother, List<Hero> child, int stillbornCount)
        {
            if (MCMSettings.Instance.ChildJoinMotherClan && mother != null && mother.Clan != null && child.Count > 0)
            {
                foreach (var hero in child)
                {
                    hero.Clan = mother.Clan;
                    hero.Culture = mother.Clan.Culture;
                }
            }
        }
    }
}